﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace VCDIFF.Tests
{
    /// <summary>
    /// Source : http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5(VS.80).aspx
    /// </summary>
    class CheckSumMD5
    {
        // Hash an input string and return the hash as
        // a 32 character hexadecimal string.
        public static string getMd5Hash(string inputFile)
        {
            FileStream fs = File.Open(inputFile, FileMode.Open, FileAccess.Read);                        

            try
            {
                // Create a new instance of the MD5CryptoServiceProvider object.
                MD5 md5Hasher = MD5.Create();

                // Convert the input string to a byte array and compute the hash.
                byte[] data = md5Hasher.ComputeHash(fs);

                // Create a new Stringbuilder to collect the bytes
                // and create a string.
                StringBuilder sBuilder = new StringBuilder();
                byte[] checkSumData = new byte[data.Length];
                // Loop through each byte of the hashed data 
                // and format each one as a hexadecimal string.
                foreach (byte b in data)
                sBuilder.Append(b.ToString("x2"));
                return sBuilder.ToString();
            }

            finally
            {
                fs.Close();
            }
        }

        // Verify integrity between two files.
        public static bool verifyIntegrity(string original, string modified)
        {
            // Hash the both files.
            string hashOfOriginal = getMd5Hash(original);
            string hashOfModified = getMd5Hash(modified);
            
            // Create a StringComparer an comare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfOriginal, hashOfModified))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        // Verify a hash against a rebuild file and the md5 of the modified file
        public static bool verifyMd5Hash(string rebuild, string hashOfModified)
        {
            // Hash the input.
            string hashOfRebuild = getMd5Hash(rebuild);

            // Create a StringComparer an comare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfRebuild, hashOfModified))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

    }
}
